<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/11 0011
 * Time: 11:58
 */

namespace app\index\controller;


use think\Controller;
use think\exception\ErrorException;
use think\Validate;
use app\index\model\Member as MemberModel;
use app\index\model\Taoorder as TaoorderModel;
use app\index\model\Nav as NavModel;
use think\Request;
use Endroid\QrCode\QrCode;
class Member extends Controller
{
    public function _initialize()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录',url('login/member_login'));
        }
        $MemberMd = new MemberModel();
        $member = $MemberMd->find(session('userid'));
        $member['encryption_mobile'] = substr_replace($member["mobile"], '****', 3, 4);
        $this->assign('member', $member);
        $navModel = new NavModel();
        // 获取导航栏信息
        $NavList = $navModel->findNavList();
        $this->assign('NavList', $NavList);
    }

    /**
     * 个人首页
     * @return array|mixed|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        return view();
    }

    /**
     * 个人设置
     * @return array|mixed|\think\response\View
     */
    public function set()
    {
        return view();
    }

    /**
     * 修改名称
     * @return array|mixed|\think\response\Json|\think\response\View
     */
    public function set_name()
    {
        if(request()->isPost()){
            $username = input("post.username");
            $token = input("post.token");
            $data = [
                'username'  => $username,
                '__token__' => $token,
            ];
            $rule = [
                'username'    => 'require|max:12',
                '__token__' => 'token',
            ];
            $msg = [
                'username.require'   => '昵称不能为空！',
                'username.max'       => '昵称最大长度为12！',
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }
            $MemberMd = new MemberModel();
            $item = [
                'userid' => session('userid'),
                'username' => $username
            ];
            if ($MemberMd->edit($item)) {
                return json(array('code' => 200, 'msg' => '修改成功'));
            } else {
                return json(array('code' => 0, 'msg' => '修改失败'));
            }
        }
        return view();
    }

    /**
     * 修改签名
     * @return array|mixed|\think\response\Json|\think\response\View
     */
    public function set_autograph()
    {
        if(request()->isPost()){
            $description = trim(input("post.description"));
            $token = input("post.token");
            $data = [
                'description'  => $description,
                '__token__' => $token,
            ];
            $rule = [
                'description'    => 'max:200',
                '__token__' => 'token',
            ];
            $msg = [
                'description.max'       => '签名字数最多65字数！',
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }
            $MemberMd = new MemberModel();
            $item = [
                'userid' => session('userid'),
                'description' => $description
            ];
            if ($MemberMd->edit($item)) {
                return json(array('code' => 200, 'msg' => '修改成功'));
            } else {
                return json(array('code' => 0, 'msg' => '修改失败'));
            }
        }
        return view();
    }

    /**
     * 绑定支付宝
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function set_alipay()
    {
        if(request()->isPost()){
            $alipay_name = trim(input("post.alipay_name"));
            $alipay_no = trim(input("post.alipay_no"));
            //TODO 这里需要先验证手机号验证码
            $code = trim(input("post.code"));
            $mobile = session('mobile');

            $data = [
                'code' => $code,
                '__token__' => input("post.token"),
            ];
            $rule = [
                'code' => 'require',
                '__token__' => 'token',
            ];
            $msg = [
                'code.require' => '请输入验证码',
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }
            $MemberMd = new MemberModel();
            $user = $MemberMd->where('alipay_no', $alipay_no)->find();
            if(!$user){
                $item = [
                    'userid' => session('userid'),
                    'alipay_name' => $alipay_name,
                    'alipay_no' => $alipay_no
                ];

                if ($MemberMd->edit($item)) {
                    return json(array('code' => 200, 'msg' => '绑定成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '绑定失败'));
                }
            }else{
                return json(array('code' => 0, 'msg' => '此支付宝帐号已有用户绑定'));
            }
        }
        return view();
    }


    /**
     * 绑定微信
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function set_wechat()
    {
        if(request()->isPost()){
            $wechat_name = trim(input("post.wechat_name"));
            $wechat_no = trim(input("post.wechat_no"));
            //TODO 这里需要先验证手机号验证码
            $code = trim(input("post.code"));
            $mobile = session('mobile');

            $data = [
                'code' => $code,
                '__token__' => input("post.token"),
            ];
            $rule = [
                'code' => 'require',
                '__token__' => 'token',
            ];
            $msg = [
                'code.require' => '请输入验证码',
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }
            $MemberMd = new MemberModel();
            $user = $MemberMd->where('wechat_no', $wechat_no)->find();
            if(!$user){
                $item = [
                    'userid' => session('userid'),
                    'wechat_name' => $wechat_name,
                    'wechat_no' => $wechat_no
                ];
                $MemberMd = new MemberModel();
                if ($MemberMd->edit($item)) {
                    return json(array('code' => 200, 'msg' => '绑定成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '绑定失败'));
                }
            }else{
                return json(array('code' => 0, 'msg' => '此微信帐号已有用户绑定'));
            }

        }
        return view();
    }


    /**
     * 修改手机号
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function set_mobile()
    {
        if(request()->isPost()){
            $mobile = input("post.mobile");
            $code = input("post.code");
            $token = input("post.token");
            //TODO 这里需要先验证手机号验证码
            $data = [
                'mobile'  => $mobile,
                '__token__' => $token,
            ];
            $rule = [
                'mobile'    => 'require|max:11/^1[3-8]{1}[0-9]{9}$/',
                '__token__' => 'token',
            ];
            $msg = [
                'mobile.require'   => '手机号不能为空！',
                'mobile.max'       => '请输入正确的手机号！',
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }

            $MemberMd = new MemberModel();
            $user = $MemberMd->where('mobile', $mobile)->find();
            if(!$user){
                $item = [
                    'userid' => session('userid'),
                    'mobile' => $mobile,
                ];

                if ($MemberMd->edit($item)) {
                    return json(array('code' => 200, 'msg' => '绑定成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '绑定失败'));
                }
            }else{
                return json(array('code' => 0, 'msg' => '此手机号已有用户绑定'));
            }
        }
        return view();
    }

    /**
     * 修改密码
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function set_password()
    {
        if(request()->isPost()){
            $pass = input("post.pass");
            $new_pass = input("post.new_pass");
            $re_new_pass = input("post.re_new_pass");
            $token = input("post.token");

            $data = [
                'new_pass'  => $new_pass,
                're_new_pass'  => $re_new_pass,
                '__token__' => $token,
            ];
            $rule = [
                'new_pass'  => 'require|confirm:re_new_pass|length:8,16',
                '__token__' => 'token',
            ];
            $msg = [
                'new_pass.require' => '新密码不能为空！',
                'new_pass.confirm' => '新密码输入不一致！',
                'new_pass.length'  => '请输入8-16位密码！',
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }
            $MemberMd = new MemberModel();
            //验证原密码
            $user = $MemberMd->where('userid', session('userid'))->find();
            if ($user['password'] == substr(md5($pass), 8, 16)) {
                $item = [
                    'userid' => session('userid'),
                    'password' => substr(md5($new_pass), 8, 16)
                ];
                $MemberMd = new MemberModel();
                if ($MemberMd->edit($item)) {
                    return json(array('code' => 200, 'msg' => '修改成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '修改失败'));
                }
            } else {
                return json(array('code' => 0, 'msg' => '原密码错误'));
            }
        }
        return view();
    }

    /**
     * 钱包
     * @return array|mixed|\think\response\View
     */
    public function money()
    {
        return view();
    }

    public function cash()
    {
        return view();
    }

    /**
     * 粉丝
     * @return array|mixed|\think\response\View
     */
    public function fans()
    {
        return view();
    }

    /**
     * 邀请
     * @return array|mixed|\think\response\View
     */
    public function invitation()
    {
        $request = Request::instance();
        $tbkurl = $request->domain();

        try{
            //获取自己邀请码
            $MemberMd = new MemberModel();
            $invitation_code = $MemberMd->where('userid', session('userid'))->value('invitation_code');
            //带LOGO
            $url = $tbkurl.'/login/member_register?invitation_code='.$invitation_code; //二维码内容
            $errorCorrectionLevel = 'L';//容错级别
            $matrixPointSize = 6;//生成图片大小
            //生成二维码图片
            Vendor('phpqrcode.phpqrcode');
            $object = new \QRcode();

            $ad = ROOT_PATH.'public/img/'.$invitation_code.'.png';
            $object->png($url, $ad, $errorCorrectionLevel, $matrixPointSize, 2);
            $logo = ROOT_PATH.'public/img/yao1.jpg';//准备好的logo图片
            $QR = ROOT_PATH.'public/img/'.$invitation_code.'.png';//已经生成的原始二维码图

            if ($logo !== FALSE) {
                $QR = imagecreatefromstring(file_get_contents($QR));
                $logo = imagecreatefromstring(file_get_contents($logo));
                $QR_width = imagesx($QR);//二维码图片宽度
                $QR_height = imagesy($QR);//二维码图片高度
                $logo_width = imagesx($logo);//logo图片宽度
                $logo_height = imagesy($logo);//logo图片高度
                $logo_qr_width = $QR_width / 5;
                $scale = $logo_width/$logo_qr_width;
                $logo_qr_height = $logo_height/$scale;
                $from_width = ($QR_width - $logo_qr_width) / 2;
                //重新组合图片并调整大小
                imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                    $logo_qr_height, $logo_width, $logo_height);
            }
            //输出图片  带logo图片
            imagepng($QR, ROOT_PATH.'public/img/'.$invitation_code.'.png');

            //合成带logo的二维码图片跟 模板图片--------------start
            $path_1 = ROOT_PATH.'public/img/yyao.jpg';//模版图片
            $path_2 = ROOT_PATH.'public/img/'.$invitation_code.'.png';//合成的二维码图
            $image_1 = imagecreatefromjpeg($path_1);
            $image_2 = imagecreatefrompng($path_2);
            $image_3 = imageCreatetruecolor(imagesx($image_1),imagesy($image_1));
            $color = imagecolorallocate($image_3, 255, 255, 255);
            imagefill($image_3, 0, 0, $color);
            imageColorTransparent($image_3, $color);
            imagecopyresampled($image_3, $image_1, 0, 0, 0, 0, imagesx($image_1), imagesy($image_1), imagesx($image_1), imagesy($image_1));//设置背景模版位置
            imagecopymerge($image_3, $image_2, 263, 960,0, 0, imagesx($image_2), imagesy($image_2), 100);//设置二维码位置
            //合成带logo的二维码图片跟 模板图片--------------end

            //输出到本地文件夹
            $EchoPath = ROOT_PATH.'public/img/'.$invitation_code.'.png';
            imagepng($image_3,$EchoPath);
            imagedestroy($image_3);
            $invitation_img = '/public/img/'.$invitation_code.'.png';
            $MemberMd::edit_user(session("userid"),['invitation_img'=>$invitation_img]);
        }catch(ErrorException $errorException){
//            echo $errorException->getMessage();
        }

        //返回生成的路径
        $this->assign('path',$invitation_img);
        return view();
    }


    /**
     * 订单提交
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ordersub()
    {
        if(request()->isPost()){
            $order_sn = input("post.order_sn");
            $token = input("post.token");

            $data = [
                '__token__' => $token,
            ];
            $rule = [
                '__token__' => 'token',
            ];
            $msg = [
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }
            $TaoorderMod = new TaoorderModel();
            $orderItem = $TaoorderMod->where('trade_id',$order_sn)->field('id,user_id')->find();
            if($orderItem){
                if($orderItem['user_id'] == 0){
                    $item = [
                        'user_id' => session('userid')
                    ];
                    if($TaoorderMod::edit($orderItem['id'],$item)){
                        return json(array('code' => 200, 'msg' => '订单提交成功'));
                    }else{
                        return json(array('code' => 0, 'msg' => '订单提交失败，请稍后再提交或联系管理员'));
                    }
                }else{
                    return json(array('code' => 0, 'msg' => '此订单已提交，请勿重复提交'));
                }
            }else{
                return json(array('code' => 0, 'msg' => '请输入有效的订单再提交或联系管理员'));
            }
        }
        return view();
    }


    /**
     * 订单列表
     * @return array|mixed|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderlist()
    {
        $TaoorderMod = new TaoorderModel();
        // 所有订单
        $TaoorderList = $TaoorderMod->where('user_id',session('userid'))->order('establish_time desc')->field('trade_id,item_title,alipay_total_price,establish_time,tkAlimmShareRate,seller_shop_title,tk_status')->select();
        foreach($TaoorderList as $taoKey=>$taoVal){
            switch ($taoVal['tk_status']) {
                case 3 : $TaoorderList[$taoKey]['tk_status'] = '已结算';$TaoorderList[$taoKey]['class_status'] = 'al_status1';break;
                case 12 : $TaoorderList[$taoKey]['tk_status'] = '已付款';$TaoorderList[$taoKey]['class_status'] = 'al_status';break;
                case 13 : $TaoorderList[$taoKey]['tk_status'] = '已失效';$TaoorderList[$taoKey]['class_status'] = 'al_statu3';break;
                case 14 : $TaoorderList[$taoKey]['tk_status'] = '已收货';$TaoorderList[$taoKey]['class_status'] = 'al_statu2';break;
            }
        }
        $this->assign('TaoorderList',$TaoorderList);
        return view();
    }

    /**
     * 意见反馈
     * @return array|mixed|\think\response\View
     */
    public function feedback()
    {
        return view();
    }

    /**
     * 关于我们
     * @return array|mixed|\think\response\View
     */
    public function about()
    {
        return view();
    }

}